<?php
require_once("ordersInit.php");
require_once("config.php");
require_once('wappay/service/AlipayTradeService.php');


logs("Alipay begin notify -----------");
logs('请求参数: '.http_build_query($_POST));

$arr          = $_POST;
$alipaySevice = new AlipayTradeService($config); 
$alipaySevice->writeLog(var_export($_POST,true));
$result = $alipaySevice->check($arr);

if($result){
    //交易状态
    $out_trade_no = trim($_POST['out_trade_no']);
    //支付宝交易号
    $trade_no     = trim($_POST['trade_no']);
    //交易状态
    $trade_status = trim($_POST['trade_status']);
    //商户本身
    $app_id       = trim($_POST['app_id']);
    //商户ID
    $seller_id    = trim($_POST['seller_id']);
    //交易金额
    $total_amount = trim($_POST['total_amount']);

    if($app_id != APP_ID){
        echo "fail";
        logs('支付宝ID异常: '.json_encode($arr));
        die();
    }
    
    if($seller_id != SELLER_ID){
        echo "fail";
        logs('支付宝商户ID异常: '.json_encode($arr));
        die();
    }


    //验证支付状态
    if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {

            $timestamp          =  time().mt_rand(1000,9999);
            $data['timestamp']  = $timestamp;
            $data['sign_code']  = serve_sign($timestamp);   
            $data['order_no']   = $out_trade_no;

            $url = HOST_URL.'/mobile/api/v1/Alipay.php?mode=callbackOrderInfo';
            $rel = curlPost($url, $data);
            if($rel['code'] != 200) {
                echo "fail";
                logs('订单检测异常: '.json_encode($rel));
                die();
            }

            //验证金额
            $order = $rel['data']['order'];
            if($total_amount != $order['order_amount'] && AliPay_Debug != true) {
                echo "fail";
                logs('订单金额异常: '.json_encode($arr));
                die();
            }

            //是否已支付完成
            if($order['pay_status'] == 2){
                echo "success";
                logs('订单已完成: '.json_encode($arr));
                die();
            }

            $url = HOST_URL. '/mobile/api/v1/Alipay.php?mode=saveOrder';
            $timestamp1          = time().mt_rand(1000,9999);
            $data1['timestamp']  = $timestamp;
            $data1['sign_code']  = serve_sign($timestamp);   
            $data1['order_no']   = $out_trade_no;
            $data1['trade_no']   = $trade_no;
            
            $rel = curlPost($url, $data1);
            if($rel['code'] != 200){
                logs('订单异常: '.json_encode($rel));
                die("fail");die();
            }

        echo "success";die();
    }else{
        echo "fail";die();
    }

}else{
    echo "fail";die();
}

logs("Alipay end notify -----------");


?>

